package com.zimsoft.strato.admin.deploy.v1_0_0.comm;

import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.logging.Log4jFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.jdbc.datasource.v1_0_0.DataSourceFactory;
import com.strato.transaction.v1_0_0.api.jdbc.DataSourceTransactionManager;
import com.strato.transaction.v1_0_0.mvc.TransactionInterceptor;

public class Activator implements BundleActivator {

	@Override
	public void start(BundleContext bundleContext) throws Exception {
		DruidDataSource datasource=new DruidDataSource();
		datasource.setUrl(GlobalEnvironment.getInstance().resolveString("${strato.datasource.admin.url}"));
		datasource.setUsername(GlobalEnvironment.getInstance().resolveString("${strato.datasource.admin.username}"));
		datasource.setPassword(GlobalEnvironment.getInstance().resolveString("${strato.datasource.admin.password}"));
		datasource.setMaxActive(GlobalEnvironment.getInstance().resolveInteger("${strato.datasource.admin.maxActive}"));
		
		datasource.setDefaultAutoCommit(false);
		datasource.setUseGlobalDataSourceStat(true);
		
		setDataSourceProxyFilters(datasource);
		datasource.init();
		DataSourceFactory.getInstance().setDataSource("strato.admin", datasource);
		
		
		TransactionInterceptor txInterceptor=new TransactionInterceptor();
		DataSourceTransactionManager txManager=new DataSourceTransactionManager();
		txInterceptor.setTransactionManager(txManager);
		BundleUtil.exportServices(bundleContext, txInterceptor, null, null);
		BundleUtil.exportServices(bundleContext, txManager, null, null);
		
	}

	private void setDataSourceProxyFilters(DruidDataSource datasource) {
		List<Filter> proxyFilters = new ArrayList<Filter>();
		StatFilter statFilter = new StatFilter();
		statFilter.setMergeSql(true);
		statFilter.setLogSlowSql(true);
		statFilter.setSlowSqlMillis(10000);
		
		proxyFilters.add(statFilter);
	
		Log4jFilter log4jFilter = new Log4jFilter();
		proxyFilters.add(log4jFilter);
		
		datasource.setProxyFilters(proxyFilters);
		
		//JdbcDataSourceStat
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
	}

}
